package com.pureut.production.service.impl;


import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.bean.BeanUtils;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.equipment.api.FeignEquipmentService;
import com.pureut.production.domain.ProcessPropertyCard;
import com.pureut.production.domain.ProcessSheet;
import com.pureut.production.domain.ProcessTempleteDrviceCard;
import com.pureut.production.domain.dto.*;
import com.pureut.production.domain.dto.equipment.GetDeviceInfoDto;
import com.pureut.production.domain.vo.*;
import com.pureut.production.mapper.*;
import com.pureut.production.service.ProcessPropertyCardService;
import com.pureut.production.service.ProcessSheetService;
import com.pureut.production.service.ProcessTempleteDrviceCardService;
import com.pureut.system.api.FeignService;
import com.pureut.system.api.domain.SysDictData;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 工艺卡
 *
 * @author: CM
 * @date: 2023/2/17  13:41
 */
@Service
public class ProcessSheetServiceImpl extends ServiceImpl<ProcessSheetMapper, ProcessSheet> implements ProcessSheetService {

    /**
     * 工艺卡mapper
     */
    @Resource
    private ProcessSheetMapper processSheetMapper;

    /**
     * 工艺卡模板mapper
     */
    @Resource
    private ProcessCardTempleteMapper processCardTempleteMapper;


    /**
     * 基础模块Fegin
     */
    @Resource
    FeignService feignService;

    /**
     * 工艺卡关联设备mapper
     */
    @Resource
    private ProcessTempleteDrviceCardMapper processTempleteDrviceCardMapper;

    /**
     * 工艺卡设备Service
     */
    @Resource
    private ProcessTempleteDrviceCardService processTempleteDrviceCardService;

    /**
     * 工艺卡设备属性
     */
    @Resource
    private ProcessPropertyCardService processPropertyCardService;

    /**
     * 工艺卡设备属性mapper
     */
    @Resource
    private ProcessPropertyCardMapper processPropertyCardMapper;

    @Resource
    private SysShopModelingMapper sysShopModelingMapper;

    @Resource
    private OperationProcessMapper operationProcessMapper;

    @Resource
    private MaterialFinishedMapper materialFinishedMapper;

    //设备feign
    @Resource
    FeignEquipmentService feignEquipmentService;


    /**
     * 新增工艺卡
     *
     * @param processSheetVo
     * @return
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(ProcessSheetVo processSheetVo) throws Exception {

        ProcessSheet processSheet = new ProcessSheet();
        BeanUtils.copyProperties(processSheetVo, processSheet);
        //工艺卡编码
        String cardCode = processSheetVo.getMaterialCode() + "-" + processSheetVo.getProductionLine();
        processSheet.setProcessCardCoding(cardCode);
        processSheet.setDeptId(SecurityUtils.getDeptId());
        //判断改工艺卡编码是否已经存在
        ProcessSheet processSheet1 = processSheetMapper.selectOne(new QueryWrapper<ProcessSheet>().lambda().eq(ProcessSheet::getProcessCardCoding, cardCode));
        if (processSheet1 != null) {
            throw new GlobalException("该工艺卡编码已经存在");
        }
        boolean save = save(processSheet);

        if (save) {

            PublicProcessVo publicProcessVo = processSheetVo.getPublicProcessVo();
            if (publicProcessVo != null) {

                List<ProcessCardTempleteVo> list = publicProcessVo.getList();

                for (ProcessCardTempleteVo processCardTempleteVo : list) {
                    //保存工艺卡关联设备
                    ProcessTempleteDrviceCard processTempleteDrviceCard = new ProcessTempleteDrviceCard();
                    //添加设备编码
                    processTempleteDrviceCard.setDrviceCode(processCardTempleteVo.getDeviceCode());
                    //添加工艺编码
                    processTempleteDrviceCard.setProcessTempleteId(cardCode);

                    //保存工艺设备关联表
                    processTempleteDrviceCardService.save(processTempleteDrviceCard);

                    //设备属性集合
                    List<ProcessPropertyVo> processList = processCardTempleteVo.getProcessList();
                    List<ProcessPropertyCard> processPropertyList = new ArrayList<>();
                    for (ProcessPropertyVo processPropertyVo : processList) {
                        ProcessPropertyCard processPropertyCard = new ProcessPropertyCard();
                        processPropertyCard.setProperty(processPropertyVo.getDeviceAddedit());
                        processPropertyCard.setValue(processPropertyVo.getValue());
                        processPropertyCard.setTempleteDrviceId(processTempleteDrviceCard.getId());
                        processPropertyList.add(processPropertyCard);
                    }
                    processPropertyCardService.saveBatch(processPropertyList);
                }
            }
        }
        return save;
    }

    /**
     * 修改工艺卡
     *
     * @param processSheetVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean edit(ProcessSheetVo processSheetVo) {
        //通过id查出工艺卡
        ProcessSheet processSheet = processSheetMapper.selectById(processSheetVo.getProcessCardId());
        //修改工艺卡名称
        processSheet.setProcessCardName(processSheetVo.getProcessCardName());
        //修改工艺流程
        processSheet.setFlowId(processSheetVo.getFlowId());

        //修改线别编码
        processSheet.setProductionLine(processSheetVo.getProductionLine());

        processSheet.setMaterialCode(processSheetVo.getMaterialCode());
        processSheet.setProductionLevel(processSheetVo.getProductionLevel());


        //配置工艺参数
        processSheet.setProcessStatus(processSheetVo.getProcessStatus());
        boolean b = updateById(processSheet);

        if (b) {
            //获取工艺卡编码
            String processCardCoding = processSheet.getProcessCardCoding();

            //删除工艺卡设备和属性
            //获取工艺卡设备关联表
            List<ProcessTempleteDrviceCard> processTempleteDrviceList = processTempleteDrviceCardMapper.selectList(new QueryWrapper<ProcessTempleteDrviceCard>().lambda().eq(ProcessTempleteDrviceCard::getProcessTempleteId, processCardCoding));

            //设备
            for (ProcessTempleteDrviceCard processTempleteDrvice : processTempleteDrviceList) {

                List<ProcessPropertyCard> processPropertyList = processPropertyCardMapper.selectList(new QueryWrapper<ProcessPropertyCard>().lambda().eq(ProcessPropertyCard::getTempleteDrviceId, processTempleteDrvice.getId()));

                //删除设备属性表
                processPropertyCardMapper.deleteBatchIds(processPropertyList);
            }
            //删除设备工艺表
            int delete = processTempleteDrviceCardMapper.deleteBatchIds(processTempleteDrviceList);

            if (delete > 0) {
                PublicProcessVo publicProcessVo = processSheetVo.getPublicProcessVo();
                if (publicProcessVo != null) {
                    List<ProcessCardTempleteVo> list = publicProcessVo.getList();

                    for (ProcessCardTempleteVo processCardTempleteVo : list) {
                        //保存工艺卡模板关联设备
                        ProcessTempleteDrviceCard processTempleteDrvice = new ProcessTempleteDrviceCard();
                        //添加设备编码
                        processTempleteDrvice.setDrviceCode(processCardTempleteVo.getDeviceCode());
                        //添加工艺卡模板id
                        processTempleteDrvice.setProcessTempleteId(processSheet.getProcessCardCoding());

                        //保存工艺设备关联表
                        processTempleteDrviceCardService.save(processTempleteDrvice);

                        //设备属性集合
                        List<ProcessPropertyVo> processList = processCardTempleteVo.getProcessList();
                        List<ProcessPropertyCard> processPropertyList = new ArrayList<>();
                        for (ProcessPropertyVo processPropertyVo : processList) {
                            ProcessPropertyCard processProperty = new ProcessPropertyCard();
                            processProperty.setProperty(processPropertyVo.getDeviceAddedit());
                            processProperty.setValue(processPropertyVo.getValue());
                            processProperty.setTempleteDrviceId(processTempleteDrvice.getId());
                            processPropertyList.add(processProperty);
                        }
                        processPropertyCardService.saveBatch(processPropertyList);
                    }
                }
            }
        }

        return b;
    }

    /**
     * 删除工艺卡
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int remove(String ids) {
        List<String> list = Arrays.asList(ids.split(","));
        //删除属性明细
        for (String s : list) {
            long id = Long.parseLong(s);
            //查询工艺设备属性
            ProcessSheet processSheet = processSheetMapper.selectById(id);
            //查出关联的设备
            List<ProcessTempleteDrviceCard> processTempleteDrviceCards = processTempleteDrviceCardMapper.selectList(new QueryWrapper<ProcessTempleteDrviceCard>().lambda().eq(ProcessTempleteDrviceCard::getProcessTempleteId, processSheet.getProcessCardCoding()));
            for (ProcessTempleteDrviceCard processTempleteDrviceCard : processTempleteDrviceCards) {
                //删除属性
                processPropertyCardMapper.delete(new QueryWrapper<ProcessPropertyCard>().lambda().eq(ProcessPropertyCard::getTempleteDrviceId, processTempleteDrviceCard.getId()));
            }
            //删除设备信息
            int delete = processTempleteDrviceCardMapper.delete(new QueryWrapper<ProcessTempleteDrviceCard>().lambda().eq(ProcessTempleteDrviceCard::getProcessTempleteId, processSheet.getProcessCardCoding()));
        }
        return processSheetMapper.deleteBatchIds(list);
    }

    /**
     * 查看工艺卡
     *
     * @param id
     * @return
     */
    @Override
    public PublicProcessDto getView(Long id) {

        //通过id查出工艺编码，工艺卡名称，工艺流程，生产线别，生产阶别，物料编码，物料名称，物料规格
        ProcessSheetDto processSheetDto = processSheetMapper.getProcessSheet(id);

        PublicProcessDto publicProcessDto = new PublicProcessDto();
        List<SysDictData> statusArray = DictUtils.getDictCache("quality_production_level");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //生产阶别
        publicProcessDto.setProductionLevel(processSheetDto.getProductionLevel());
        publicProcessDto.setProcessCardId(id);
        //生产线别
        publicProcessDto.setProductionLine(processSheetDto.getProductionLine());

        publicProcessDto.setProcessCardName(processSheetDto.getProcessCardName());
        publicProcessDto.setProcessCardCoding(processSheetDto.getProcessCardCoding());
        publicProcessDto.setMaterialCode(processSheetDto.getMaterialCode());
        publicProcessDto.setMaterialName(processSheetDto.getMaterialName());
        publicProcessDto.setMaterialSpec(processSheetDto.getMaterialSpec());
        publicProcessDto.setFlowName(processSheetDto.getFlowName());
        publicProcessDto.setFlowId(processSheetDto.getFlowId());
        //获取设备+属性集合
        List<ProcessCardTempleteDto> list = new ArrayList<>();

        //获取设备编码到list集合中
        List<ProcessTempleteDrviceCard> processTempleteDrviceList = processTempleteDrviceCardMapper.selectList(new QueryWrapper<ProcessTempleteDrviceCard>().lambda().eq(ProcessTempleteDrviceCard::getProcessTempleteId, processSheetDto.getProcessCardCoding()));
        for (ProcessTempleteDrviceCard processTempleteDrvice : processTempleteDrviceList) {
            ProcessCardTempleteDto processCardTempleteDto = new ProcessCardTempleteDto();
            //添加设备编码
            processCardTempleteDto.setDeviceCode(processTempleteDrvice.getDrviceCode());

            AjaxResult deviceInfo = feignEquipmentService.getDeviceInfo(processTempleteDrvice.getDrviceCode());
            GetDeviceInfoDto getDeviceInfoDto = JSON.parseObject(JSON.toJSONString(deviceInfo.get("data")), GetDeviceInfoDto.class);

            if (getDeviceInfoDto==null){
                throw new  GlobalException("未查到相关设备信息");
            }

            processCardTempleteDto.setDeviceName(getDeviceInfoDto.getDeviceName());
            processCardTempleteDto.setDeviceType(getDeviceInfoDto.getDeviceType());


            //获取设备属性信息
            List<ProcessPropertyDto> processList = new ArrayList<>();

            //查询当前设备编码对应的属性和值
            List<ProcessPropertyCard> processPropertyList = processPropertyCardMapper.selectList(new QueryWrapper<ProcessPropertyCard>().lambda().eq(ProcessPropertyCard::getTempleteDrviceId, processTempleteDrvice.getId()));
            for (ProcessPropertyCard processPropertyCard : processPropertyList) {
                ProcessPropertyDto processPropertyDto = new ProcessPropertyDto();
                processPropertyDto.setDeviceAddedit(processPropertyCard.getProperty());
                processPropertyDto.setValue(processPropertyCard.getValue());

                processList.add(processPropertyDto);
            }
            processCardTempleteDto.setProcessList(processList);
            list.add(processCardTempleteDto);
        }

        publicProcessDto.setList(list);

        return publicProcessDto;
    }


    /**
     * 工艺卡列表查询
     *
     * @param processSheetVo
     * @return
     */
    @Override
    @DataScope(deptAlias = "t1")
    public List<ProcessSheetDto> selectSheetList(ProcessSheetVo processSheetVo) {
        List<ProcessSheetDto> processSheetDtoList = processSheetMapper.selectSheetList(processSheetVo);

        List<SysDictData> statusArray = DictUtils.getDictCache("quality_production_level");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (ProcessSheetDto processSheetDto : processSheetDtoList) {
            processSheetDto.setProductionLevelDict(statusMap.get(processSheetDto.getProductionLevel()));
        }
        return processSheetDtoList;
    }

    /**
     * 参数配置，填写设备属性
     *
     * @param publicProcessVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean editTemplete(PublicProcessVo publicProcessVo) {
        /*
        //获取工艺卡模板id
        Long id = publicProcessVo.getTempleteId();

        //删除工艺卡设备和属性
        //获取工艺卡设备关联表
        List<ProcessTempleteDrvice> processTempleteDrviceList = processTempleteDrviceMapper.selectList(new QueryWrapper<ProcessTempleteDrvice>().lambda().eq(ProcessTempleteDrvice::getProcessTempleteId, id));

        //设备
        for (ProcessTempleteDrvice processTempleteDrvice : processTempleteDrviceList) {

            List<ProcessProperty> processPropertyList = processPropertyMapper.selectList(new QueryWrapper<ProcessProperty>().lambda().eq(ProcessProperty::getTempleteDrviceId, processTempleteDrvice.getId()));

            //删除设备属性表
            processPropertyMapper.deleteBatchIds(processPropertyList);
        }
        //删除设备工艺表
        int delete = processTempleteDrviceMapper.deleteBatchIds(processTempleteDrviceList);

        if (delete>0) {

            List<ProcessCardTempleteVo> list = publicProcessVo.getList();

            for (ProcessCardTempleteVo processCardTempleteVo : list) {
                //保存工艺卡模板关联设备
                ProcessTempleteDrvice processTempleteDrvice = new ProcessTempleteDrvice();
                //添加设备编码
                processTempleteDrvice.setDrviceCode(processCardTempleteVo.getDrviceCode());
                //添加工艺卡模板id
                processTempleteDrvice.setProcessTempleteId(id);

                //保存工艺设备关联表
                processTempleteDrviceService.save(processTempleteDrvice);

                //设备属性集合
                List<ProcessPropertyVo> processList = processCardTempleteVo.getProcessList();
                List<ProcessProperty> processPropertyList = new ArrayList<>();
                for (ProcessPropertyVo processPropertyVo : processList) {
                    ProcessProperty processProperty = new ProcessProperty();
                    processProperty.setProperty(processPropertyVo.getDrviceAddedit());
                    processProperty.setValue(processPropertyVo.getValue());
                    processProperty.setTempleteDrviceId(processTempleteDrvice.getId());
                    processPropertyList.add(processProperty);
                }
                processPropertyService.saveBatch(processPropertyList);
            }
        }
        return delete>0;
        */
        return true;
    }

    /**
     * 根据生产阶别查出线别
     *
     * @param productionLevel
     * @return
     */
    @Override
    public List<GetLineDto> getLine(String productionLevel) {
        List<GetLineDto> list = sysShopModelingMapper.getLine(productionLevel);
        return list;
    }

    /**
     * 根据生产阶别查工艺流程
     *
     * @param productionLevel
     * @return
     */
    @Override
    public List<GetProcessDto> getProcess(String productionLevel) {
        List<GetProcessDto> list = operationProcessMapper.getProcess(productionLevel);
        return list;
    }

    /**
     * 查询物料信息
     *
     * @param materialInfoVo
     * @return
     */
    @Override
    public List<MaterialInfoDto> getMaterialInfo(MaterialInfoVo materialInfoVo) {
        List<MaterialInfoDto> list = materialFinishedMapper.getInfo(materialInfoVo);
        return list;
    }


}
